// src/generators/subApp.ts
import inquirer from 'inquirer';
import path from 'path';
import { logger } from '../utils/logger';
import { validateProjectName, writeConfig, ProjectConfig } from '../utils/config';
import { copyTemplate } from '../utils/template';
import { checkDirectoryExists, createProjectDirectory, updatePackageJson } from './utils';

// 子应用配置选项
interface SubAppAnswers {
  projectName: string;
  framework: 'react' | 'vue' | 'vanilla';
  port: string;
  features: string[];
}

const subAppGenerator = async (): Promise<void> => {
  logger.info('开始创建子应用...');
  
  // 交互式询问配置
  const answers = await inquirer.prompt<SubAppAnswers>([
    {
      type: 'input',
      name: 'projectName',
      message: '请输入子应用名称:',
      default: 'sub-app',
      validate: (input: string) => validateProjectName(input) || '项目名称验证失败'
    },
    {
      type: 'list',
      name: 'framework',
      message: '选择子应用框架:',
      choices: [
        { name: 'React', value: 'react' },
        { name: 'Vue', value: 'vue' },
        { name: '原生 JavaScript', value: 'vanilla' }
      ]
    },
    {
      type: 'input',
      name: 'port',
      message: '请输入开发服务器端口:',
      default: (answers: Partial<SubAppAnswers>) => {
        // 根据框架设置默认端口
        const defaultPorts = {
          react: '7101',
          vue: '7102', 
          vanilla: '7103'
        };
        return defaultPorts[answers.framework as keyof typeof defaultPorts] || '7101';
      },
      validate: (input: string) => {
        const port = parseInt(input);
        return (port > 0 && port < 65536) ? true : '请输入有效的端口号 (1-65535)';
      }
    },
    {
      type: 'checkbox',
      name: 'features',
      message: '选择需要集成的功能:',
      choices: [
        { name: 'TypeScript', value: 'typescript', checked: true },
        { name: '代码规范(ESLint + Prettier)', value: 'lint', checked: true },
        { name: '微前端生命周期', value: 'micro-lifestyle', checked: true }
      ]
    }
  ]);

  const targetDir = path.join(process.cwd(), answers.projectName);
  
  // 检查目录是否存在
  if (await checkDirectoryExists(targetDir)) {
    const { overwrite } = await inquirer.prompt<{ overwrite: boolean }>([
      {
        type: 'confirm',
        name: 'overwrite',
        message: `目录 ${answers.projectName} 已存在，是否覆盖?`,
        default: false
      }
    ]);
    
    if (!overwrite) {
      logger.info('操作已取消');
      return;
    }
  }

  try {
    // 创建项目目录
    await createProjectDirectory(targetDir);
    
    // 确定模板名称
    const templateName = `${answers.framework}-child`;
    const templateVariables = {
      projectName: answers.projectName,
      port: answers.port
    };
    
    // 复制模板文件
    await copyTemplate(templateName, targetDir, templateVariables);
    
    // 更新配置文件
    const projectConfig: ProjectConfig = {
      projectName: answers.projectName,
      type: 'sub',
      framework: answers.framework,
      port: parseInt(answers.port),
      features: answers.features
    };
    
    await writeConfig(targetDir, projectConfig);
    
    // 更新package.json
    await updatePackageJson(targetDir, {
      name: answers.projectName,
      scripts: {
        dev: `vite --port ${answers.port}`
      }
    });
    
    // 显示成功信息
    logger.success(`✅ ${answers.framework} 子应用创建成功!`);
    logger.info(`\n下一步操作:`);
    logger.info(`  cd ${answers.projectName}`);
    logger.info(`  npm install  # 或使用 pnpm/yarn`);
    logger.info(`  npm run dev\n`);
    
  } catch (error) {
    logger.error('创建子应用失败:', error);
    throw error;
  }
};

export default subAppGenerator;